package com.springbootee.uitl;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jdk.nashorn.internal.parser.Token;
import lombok.Data;
import lombok.experimental.Accessors;

import javax.security.auth.login.CredentialNotFoundException;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    //秘钥
     private static final  String TOKEN_SECRET="createbootspringmybatis123123";
     private  static  final  String TOKEN_ISSUER="xiajc";

     @Data
    @Accessors(chain = true)
    public static class TokenDate{
        private boolean success;
        private String reason;
        private Date time;
        private JSONObject data;
     }


    /**
     *生成token
     * @param json
     * @retrun
     */
    public static String encodeToken(String json,Long expireTime){
        JWTCreator.Builder builder= JWT.create();
        builder=builder.withIssuer(TOKEN_SECRET);
        Algorithm algorithm=Algorithm.HMAC256(TOKEN_ISSUER);
        if (expireTime != null && expireTime > 0 ){
         Date date=new Date(System.currentTimeMillis() + expireTime);
         builder=builder.withExpiresAt(date);
        }else {
            Date date=new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 30L);
           builder=builder.withExpiresAt(date);
        }
        //生成加密算法
        builder=builder.withClaim("date",json);
        return builder.sign(algorithm);
    }
    /**
     * 加密算法
     * @param  json
     * @return
     */
    public  static String encodeToken(String json){
        return encodeToken(json,null);
    }
    /**
     * 解密算法
     * @param token
     * @return
     */
    public  static TokenDate decodeToken(String token) throws Exception{
        //秘钥以及算法
        try {
        Algorithm algorithm=Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier=JWT.require(algorithm)
                    .withIssuer(TOKEN_ISSUER)
                    .build();
            DecodedJWT decodedJWT=verifier.verify(token);
            Map<String, Claim> map=decodedJWT.getClaims();
            String date=map.get("date").asString();
            if (decodedJWT.getExpiresAt() !=null && decodedJWT.getExpiresAt().getTime() < new  Date().getTime()){
                return  new TokenDate().setData(JSONObject.parseObject(date)).setSuccess(false)
                        .setReason("身份验证已过期，请重新验证身份");
            }
            return  new TokenDate().setData(JSONObject.parseObject(date)).setSuccess(true)
                    .setReason("身份验证通过");
        }catch (Exception e){
            return  new TokenDate().setData(null).setSuccess(false).setReason(e.getMessage());
        }
    }
}
